import base64
import uuid
import datetime

from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer  # 加密包
# from itsdangerous import SignatureExpired  # 导入解密时抛出的异常（错误，超时等）项目中我们默认无限期随时激活
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View

from utils.RabbitMQ_tasks.send_email_MQ.producer import RabbitMQ
from utils.image_code import check_code
from web import models
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSmsForm, LoginForm


def sms(request):
    """专门发短信的接口"""
    """
    发验证码短信接口
    url?mobile_phone=xxx&tpl=register    ---->注册模板id：571781
    """
    # 手机号和短信模板去form中校验
    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():
        # 已经在SendSmsForm类中去校验通过，说明短信已经发送成功了
        # 因为在form中完成了短信发送以及redis存验证码(60s过期)
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


class RegisterView(View):
    """注册"""

    def get(self, request):
        """注册页面显示接口"""
        form = RegisterModelForm()
        return render(request, "register.html", {'form': form})

    def post(self, request):
        """注册接口"""
        data = request.POST
        form = RegisterModelForm(data)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            username = form.cleaned_data.get('username')
            # 验证通过，写入数据库，form组件的save除了写入到数据库，还会自动剔除数据库没有的字段比如重复密码和验证码
            # 它会返回一个instance，就是存储进库的用户对象user
            instance = form.save()
            user = models.UserInfo.objects.filter(username=username).first()
            RabbitMQ(email=email, username=username, user_id=user.id)
            data = 'https://mail.163.com/'
            if '@qq.com' in email:
                data = 'https://mail.qq.com/'
            return JsonResponse({'status': True, 'data': data})
        return JsonResponse({'status': False, 'error': form.errors})


class Active(View):
    """用户激活"""
    def get(self, request, token):
        # 进行解密，获取要激活的用户信息
        serializer = Serializer(settings.SECRET_KEY)
        info = serializer.loads(token)
        # 获取待激活用户的id
        user_id = info['confirm']
        # 根据id获取用户信息
        user = models.UserInfo.objects.filter(id=user_id).first()
        user.is_active = 1  # 激活成功
        user.save()
        # 跳转到登陆页面
        return redirect(reverse('login'))


class LoginSmsView(View):
    """验证码登录方式"""

    def get(self, request):
        form = LoginSmsForm()
        return render(request, 'login_sms.html', {'form': form})

    def post(self, request):
        form = LoginSmsForm(request.POST)
        if form.is_valid():
            mobile_phone = form.cleaned_data.get('mobile_phone')
            # 来一个手机号或者用户名把注册进去的用户找到
            user = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
            # 把用户id和用户名存入session中待使用
            request.session['user_id'] = user.id
            request.session['username'] = user.username

            return JsonResponse({'status': True, 'data': '/'})
        return JsonResponse({'status': False, 'error': form.errors})


class LoginView(View):
    """用户名密码登录"""

    def get(self, request):
        form = LoginForm(request)
        return render(request, 'login.html', {'form': form})

    def post(self, request):
        form = LoginForm(request, request.POST)
        if form.is_valid():
            return JsonResponse({'status': True, 'data': '/'})
        return JsonResponse({'status': False, 'error': form.errors})


def image_code(request):
    """生成图片验证码"""
    from io import BytesIO
    image_object, code = check_code()
    # 写进session中
    request.session['image_code'] = code
    request.session.set_expiry(60)  # 60s过期

    stream = BytesIO()
    image_object.save(stream, 'png')
    # 返回图片内容
    return HttpResponse(stream.getvalue())
